package com.upsuns.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 *@Description:<p>客户端，基于Netty的NIO模型</p>
 *@author 王旭
 *@time 2016年3月18日 下午11:56:23
 */
public class TimeClient {
	
	private String host;
	
	private int port;
	
	public TimeClient(String host, int port) {
		this.host = host;
		this.port = port;
	}
	
	public void doClient() {
		EventLoopGroup group = new NioEventLoopGroup(); //处理读写的线程组
		
		Bootstrap boot = new Bootstrap();
		boot.group(group)
			.channel(NioSocketChannel.class)
			.option(ChannelOption.TCP_NODELAY, true)
			.handler(new ChannelInitializer<SocketChannel>() {
				@Override
				protected void initChannel(SocketChannel ch) throws Exception {
					ch.pipeline().addLast(new TimeClientHandler());	
				}
			});
		
		ChannelFuture cf = null;
		try {
			cf = boot.connect(host, port).sync(); //等待连接成功
			cf.channel().closeFuture().sync(); //等待客户端连接关闭，防止任务未完成就退出
		} catch (InterruptedException e) {
			group.shutdownGracefully();
		}
		
		
	}
	
	

}
